<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\Message;
use buwang\base\AdminBaseController;

//use EasyAdmin\annotation\ControllerAnnotation;
//use EasyAdmin\annotation\NodeAnotation;
//use think\App;
use buwang\util\CommonTool;
use jianyan\excel\Excel;
use think\Exception;
use think\facade\Db;
use think\facade\View;
use buwang\base\MemberBaseController;
use app\manage\model\User as UserModel;

/**
 * @ControllerAnnotation(title="APP用户表")
 */
class User extends MemberBaseController
{
    use \buwang\traits\Crud;

    protected $relationSearch = true;
    protected $member_id = 0;

    public function initialize()
    {
        parent::initialize();
        $this->layout && $this->app->view->engine()->layout($this->layout);
        $this->model = new UserModel();
        $this->member_id = $this->user->top_id;//租户id
        $this->assign('getMemberMiniappList', $this->model->getMemberMiniappList($this->member_id));

        $this->assign('getStatusList', $this->model->getStatusList());

    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->withJoin('memberMiniapp', 'LEFT')
                ->where('memberMiniapp.member_id', $this->member_id)
                ->where($where)
                ->count();
            $list = $this->model
                ->withJoin('memberMiniapp', 'LEFT')
                ->where('memberMiniapp.member_id', $this->member_id)
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'total' => $count,
                'list' => $list,
            ];
            return $this->success('success', $data);
        }
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $post = reform_keys($post);
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                return $this->error('保存失败:' . $e->getMessage());
            }
            if (!$save) return $this->error('保存失败');
            return $this->success('保存成功');
        }
        return view();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        if ($row->isEmpty()) return $this->error('数据不存在');

        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $post = reform_keys($post);
            $rule = [];
            $this->validate($post, $rule);

            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                return $this->error('保存失败');
            }
            if (!$save) return $this->error('保存失败');
            return $this->success('保存成功');
        }
        View::assign('row', $row);
        return view();
    }


    /**
     * @NodeAnotation(title="编辑")
     */
    public function editPw($id)
    {
        $row = $this->model->find($id);
        if ($row->isEmpty()) return $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $post = reform_keys($post);
            $rule = [];
            $this->validate($post, $rule);
            if (!$post['password'] && !$post['safe_password']) return $this->error('请填写要重置的密码或安全密码');
            if ($post['password']) {
                if ($post['password'] != $post['password2']) return $this->error('两次输入的密码不一致');
            }
            if ($post['safe_password']) {
                if (!preg_match("/^\d{6}$/", $post['safe_password'])) return $this->error('请输入6位数字');
                if ($post['safe_password'] != $post['safe_password2']) return $this->error('两次输入的安全密码不一致');
            }
            try {
                unset($post['password2']);
                unset($post['safe_password2']);
//                $pwd = password_hash(md5('111111'),PASSWORD_DEFAULT);
//                var_dump(password_verify(md5('111111'),$pwd));die;
//                var_dump($post['safe_password']);die;
                //加密
                if ($post['password']) $post['password'] = password_hash(md5($post['password']), PASSWORD_DEFAULT); else unset($post['password']);
                if ($post['safe_password']) $post['safe_password'] = password_hash(md5($post['safe_password']), PASSWORD_DEFAULT); else unset($post['safe_password']);
//                var_dump($post['safe_password']);
//                var_dump(password_verify(md5('111111'),$post['safe_password']));
//                var_dump($post['safe_password']);
                $save = $row->save($post);
            } catch (\Exception $e) {
                return $this->error('保存失败');
            }
            if (!$save) return $this->error('保存失败');
            return $this->success('保存成功');
        }
        View::assign('row', $row);
        return view();
    }


    /**
     * @NodeAnotation(title="编辑余额")
     */
    public function changeMoney($id)
    {
        $row = $this->model->find($id);
        if ($row->isEmpty()) return $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $post = reform_keys($post);
            $rule = [];
            $this->validate($post, $rule);
            try {
                UserModel::changeMoney($id, $post['money'], ['系统增加余额', '系统减少余额'], ['system_add', 'system_sub']);
                UserModel::changeIntegral($id, $post['integral'], ['系统增加积分', '系统减少积分'], ['system_add', 'system_sub']);
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }
            return $this->success('保存成功');
        }
        View::assign('row', $row);
        return view();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function del($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        if ($row->isEmpty()) return $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            return $this->error('删除失败');
        }
        if (!$save) return $this->error('删除失败');
        return $this->success('删除成功');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            'id|ID' => 'require',
            'field|字段' => 'require',
            'value|值' => 'require',
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) {
            return $this->error('数据不存在');
        }
        if (!in_array($post['field'], $this->allowModifyFileds)) {
            return $this->error('该字段不允许修改：' . $post['field']);
        }
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('保存成功');
    }

    /**
     * 发送站内信
     */
    public function sendMessage($id = 0){
        if (request()->isPost()) {
            $user_id = request()->post('user_id/d', 0);
            $msg = request()->post('msg/s', '');

            if(!$user_id || !$msg) return $this->error('参数有误');

            try {
                Message::send(3, $this->uid, $user_id, $msg);
                return $this->success('发送成功');
            }catch (Exception $e){
                return $this->error($e->getMessage());
            }
        }

        View::assign('user_id', $id);
        return view();
    }
}